package util;

import book.PairOfUidAndBookId;
import com.bit.utils.FileUtils;
import constant.Constant;

public class AnalyzingBorrowedBook {
    public void storeObject(PairOfUidAndBookId[] pairOfUidAndBookIds,String filename){
        int bookUserLen=0;
        for(int i=0;i<pairOfUidAndBookIds.length;i++) {
            if (pairOfUidAndBookIds[i] != null) {
                bookUserLen++;
            }
        }
            StringBuilder jsonArray=new StringBuilder();
            for(int i=0;i<bookUserLen;i++){
                if(pairOfUidAndBookIds[i]!=null){
                    jsonArray.append(pairOfUidAndBookIds[i].toJson());
                    if(i!=bookUserLen-1){
                        jsonArray.append('\n');
                    }
                }
            }
        FileUtils.writeFile(jsonArray.toString(),filename);
    }
    //加载所有借书记录；
    public PairOfUidAndBookId[] loadObject(String filename){
        String constant=FileUtils.readFile(filename);
        if(constant==null||constant.isEmpty()){
            System.out.println("Files is empty or does no exits"+filename);
            return null;
        }
        String[] bookJsonStrings=constant.split("\n");
        PairOfUidAndBookId[] pairOfUidAndBookIds=new PairOfUidAndBookId[bookJsonStrings.length];
        for(int i=0;i< bookJsonStrings.length;i++){
            PairOfUidAndBookId pairOfUidAndBookId=new PairOfUidAndBookId();
            String[] uidAndBookIds=bookJsonStrings[i].split(",");
            pairOfUidAndBookId.setUserId(Integer.parseInt(uidAndBookIds[0]));
            pairOfUidAndBookId.setBookId(Integer.parseInt(uidAndBookIds[1]));
            pairOfUidAndBookIds[i]=pairOfUidAndBookId;
        }
        return pairOfUidAndBookIds;
    }
    public static void main1(String[] args){
        PairOfUidAndBookId[] pairOfUidAndBookIds=new PairOfUidAndBookId[2];
        pairOfUidAndBookIds[0]=new PairOfUidAndBookId(1,1001);
        pairOfUidAndBookIds[1]=new PairOfUidAndBookId(2,2002);
        AnalyzingBorrowedBook analyzingBorrowedBook=new AnalyzingBorrowedBook();
        analyzingBorrowedBook.storeObject(pairOfUidAndBookIds, Constant.BORROWED_BOOK_FILE_NAME);
    }
    public static void main(String[] args){
        AnalyzingBorrowedBook analyzingBorrowedBook=new AnalyzingBorrowedBook();
        PairOfUidAndBookId[] ret= analyzingBorrowedBook.loadObject(Constant.BORROWED_BOOK_FILE_NAME);
        for(int i=0;i< ret.length;i++){
            System.out.println(ret[i]);
        }
    }


}
